﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace PcArduinoControl
{
	class Exchange
	{
		public Command mCommand;

		public bool IsResponded
		{
			get
			{
				return (FailCode != FailCode.NoResponse);
			}
		}

		public FailCode FailCode = FailCode.NoResponse;

		public byte PacketID
		{
			get
			{
				return mCommand.Id;
			}
			internal set
			{
				mCommand.Id = value;
			}
		}

		public bool IsSent { get; set; }

		public DateTime SentAt { get; set; }

		public Exchange(Command command)
		{
			IsSent = false;
			mCommand = command;
		}

		public FailCode GetFailCode(int mstimeout)
		{
			if (!IsSent)
				return PcArduinoControl.FailCode.UnknownFail;

			while (!IsResponded)
			{
				DateTime utcNow = DateTime.UtcNow;

				if (utcNow - SentAt > TimeSpan.FromMilliseconds(mstimeout))
					return FailCode.NoResponse;
				Thread.Sleep(15);
			}
			return FailCode;
		}
	}
}
